import { defineStore } from 'pinia'

const USERS_KEY = 'fitmatch_users'
const AUTH_USER_KEY = 'fitmatch_auth_user'

function readUsers() {
  try {
    const raw = localStorage.getItem(USERS_KEY)
    return raw ? JSON.parse(raw) : []
  } catch {
    return []
  }
}

function writeUsers(users) {
  localStorage.setItem(USERS_KEY, JSON.stringify(users))
}

export const useAuthStore = defineStore('auth', {
  state: () => ({
    currentUser: loadCurrentUser(),
  }),
  getters: {
    isAuthenticated: (state) => !!state.currentUser,
  },
  actions: {
    register({ email, password, name }) {
      const users = readUsers()

      if (users.some((user) => user.email === email)) {
        throw new Error('该邮箱已被注册')
      }

      const newUser = {
        id: createId(),
        email,
        password,
        name,
        createdAt: new Date().toISOString(),
      }

      users.push(newUser)
      writeUsers(users)
      this.persistSession(newUser)
    },
    login({ email, password }) {
      const users = readUsers()
      const match = users.find(
        (user) => user.email === email && user.password === password,
      )

      if (!match) {
        throw new Error('账号或密码错误')
      }

      this.persistSession(match)
    },
    logout() {
      this.currentUser = null
      localStorage.removeItem(AUTH_USER_KEY)
    },
    persistSession(user) {
      const payload = {
        id: user.id,
        email: user.email,
        name: user.name,
        createdAt: user.createdAt,
      }
      this.currentUser = payload
      localStorage.setItem(AUTH_USER_KEY, JSON.stringify(payload))
    },
    hydrate() {
      this.currentUser = loadCurrentUser()
    },
    updateProfile(partial) {
      if (!this.currentUser) return

      const users = readUsers()
      const index = users.findIndex((user) => user.id === this.currentUser.id)
      if (index === -1) return

      const updatedUser = {
        ...users[index],
        ...partial,
      }
      users.splice(index, 1, updatedUser)
      writeUsers(users)
      this.persistSession(updatedUser)
    },
  },
})

function loadCurrentUser() {
  try {
    const raw = localStorage.getItem(AUTH_USER_KEY)
    return raw ? JSON.parse(raw) : null
  } catch {
    return null
  }
}

function createId() {
  if (typeof crypto !== 'undefined' && crypto.randomUUID) {
    return crypto.randomUUID()
  }
  return `user_${Date.now()}_${Math.random().toString(16).slice(2)}`
}
